import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/auth'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('@/layout/Layout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
            path: 'test1',
            component: () => import('@/views/test/Test1.vue'),
            meta: { title: '测试页面1', icon: 'el-icon-s-home', roles: ['admin', 'user', 'editor', 'guest'] }
          },
        {
          path: 'test-dir2',
          meta: { title: '测试目录2', icon: 'el-icon-folder' },
          children: [
            {
              path: 'test2',
              component: () => import('@/views/test/Test2.vue'),
              meta: { title: '测试页面2', icon: 'el-icon-document' }
            },
            {
              path: 'test-dir3',
              meta: { title: '测试目录3', icon: 'el-icon-folder-opened', roles: ['admin', 'user', 'editor'] },
              children: [
                {
                  path: 'test3',
                  component: () => import('@/views/test/Test3.vue'),
                  meta: { title: '测试页面3', icon: 'el-icon-tickets' }
                },
                {
                  path: 'test4',
                  component: () => import('@/views/test/Test4.vue'),
                  meta: { title: '测试页面4', icon: 'el-icon-data-line', roles: ['admin'] }
                }
              ]
            }
          ]
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  const hasToken = getToken()
  
  if (to.path === '/login') {
    if (hasToken) {
      next({ path: '/' })
    } else {
      next()
    }
    return
  }
  
  if (!hasToken) {
    next(`/login?redirect=${to.path}`)
  } else {
    const userInfo = JSON.parse(localStorage.getItem('user-base-info') || '{}')
    const requiredRoles = to.matched.reduce((roles, record) => {
      if (record.meta?.roles) {
        roles.push(...record.meta.roles)
      }
      return roles
    }, [])
    
    if (requiredRoles.length && !requiredRoles.includes(userInfo.role)) {
      next('/403')
    } else {
      next()
    }
  }
})

export default router